package com.example.onlineanswer.common.interceptor;

import com.example.onlineanswer.common.annotation.RequireRole;
import com.example.onlineanswer.common.exception.ApiException;
import com.example.onlineanswer.common.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.util.Arrays;

/**
 * 权限拦截器
 */
@Component
public class AuthInterceptor implements HandlerInterceptor {

    @Autowired
    private JwtUtil jwtUtil;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 如果不是通过HandlerMethod访问的，则直接放行
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }

        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();

        // 获取方法上的RequireRole注解
        RequireRole requireRole = method.getAnnotation(RequireRole.class);
        // 如果方法上没有，则获取类上的RequireRole注解
        if (requireRole == null) {
            requireRole = handlerMethod.getBeanType().getAnnotation(RequireRole.class);
        }

        // 如果没有RequireRole注解，则不需要权限验证，直接放行
        if (requireRole == null) {
            return true;
        }

        // 获取token
        String authHeader = request.getHeader(jwtUtil.getHeader());
        if (!StringUtils.hasText(authHeader) || !authHeader.startsWith(jwtUtil.getTokenPrefix())) {
            throw new ApiException("无效的Token");
        }

        // 解析token
        String token = authHeader.substring(jwtUtil.getTokenPrefix().length() + 1);
        if (!jwtUtil.validateToken(token)) {
            throw new ApiException("Token已过期或无效");
        }

        // 获取角色
        String role = jwtUtil.getRoleFromToken(token);
        if (role == null) {
            throw new ApiException("Token中无角色信息");
        }

        // 检查角色是否匹配
        String[] roles = requireRole.value();
        boolean hasRole = Arrays.asList(roles).contains(role);
        if (!hasRole) {
            throw new ApiException("权限不足，需要角色：" + Arrays.toString(roles));
        }

        // 将用户信息放入请求属性中，方便后续使用
        request.setAttribute("username", jwtUtil.getUsernameFromToken(token));
        request.setAttribute("role", role);

        return true;
    }
} 